import 'dart:async';

import 'package:flutter/material.dart';
import 'package:heven/api/index.dart';
import 'package:heven/model/config_model.dart';
import 'package:heven/model/goods_model.dart';
import 'package:heven/pages/vip/widget/item.dart';
import 'package:heven/pages/vip/widget/popup.dart';
import 'package:heven/utils/buyEngin.dart';
import 'package:heven/utils/index.dart';
import 'package:heven/widget/button.dart';

class VipPage extends StatefulWidget {
  const VipPage({super.key});

  @override
  State<VipPage> createState() => _VipPageState();
}

class _VipPageState extends State<VipPage> {
  int _currentIndex = 0;
  List _list = [];
  String _type = 'buy';
  int _artConsumeCoinNumber = 0;
  String _customId = '';
  late int _id;
  int _time = 0;
  int _num = 0;
  late Goods _year;
  late BuyEngin _buyEngin;
  bool _loading = false;
  @override
  void initState() {
    super.initState();
    _buyEngin = BuyEngin(onPurchaseResult: (purchase) {
      final code = purchase['code'];
      final serverVerificationData = purchase['serverVerificationData'];

      if (code == 'success' && _loading) {
        _loading = false;
        if (_type == 'buy') {
          _verification(serverVerificationData);
        } else {
          _repurchase(serverVerificationData);
        }
      } else if (code == 'error') {
        Navigator.pop(context);
      }
    });
    _buyEngin.initializeInAppPurchase();
    _fetchData();
  }

  Future<void> _fetchData() async {
    // await getConfig();
    // String? value = await Common.getStorageValue('artConsumeCoinNumber');
    // _artConsumeCoinNumber =
    //     _artConsumeCoinNumber = int.tryParse(value ?? '1') ?? 1;
    var params = {
      "type": "subscribe" //内购类型 consume 消耗型 subscribe 订阅型，默认：consume
    };
    List<Future<dynamic>> futures = [
      getGoodsList({"sign": Common.generateSign(params), ...params}),
      getConfig()
    ];

    var results = await Future.wait(futures);
    print(results[0]);
    GoodsModel json = GoodsModel.fromJson(results[0]);
    ConfigModel configModel = ConfigModel.fromJson(results[1]);
    await Common.saveStorageValue('artConsumeCoinNumber',
        configModel.artConsumeCoinNumber.value.toString());
    setState(() {
      _customId = json.list[0].customId;
      _artConsumeCoinNumber = configModel.artConsumeCoinNumber.value;
      _id = json.list[0].id;
      _list = json.list;
      _year = _list
          .where(
            (item) => item.timeType == 'annually',
          )
          .toList()[0];
    });
  }

  void _repurchase(serverVerificationData) async {
    var uid = await Common.getStorageValue('uid');
    var result =
        await repurchase({"uid": uid, "receipt_data": serverVerificationData});
    Navigator.pop(context);
  }

  void _verification(serverVerificationData) async {
    var uid = await Common.getStorageValue('uid');
    await verification({
      "uid": uid,
      "type": "subscribe", //应用内购买的类型，订阅型：subscribe，消耗型：consume
      "goods_id": _id,
      "receipt_data": serverVerificationData
    });
    Navigator.pop(context);
    Navigator.pushNamedAndRemoveUntil(
        context,
        '/home', // 你的首页路由名称
        (route) => false, // 移除所有页面
        arguments: {"index": 1});
  }

  void _buy(String _customId) {
    Common.loadingDialog(context);
    _loading = true;
    _type = "buy";
    _buyEngin.buyProduct(_customId);
  }

  @override
  void dispose() {
    _buyEngin.onClose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 60,
        leadingWidth: 53,
        leading: GestureDetector(
          onTap: () async {
            //  _countdown();

            _time = int.parse(await Common.getStorageValue('time') ?? '0');
            _showDialog(context);
          },
          child: Padding(
            padding: const EdgeInsets.only(left: 23),
            child: Image.asset(
              'assets/images/close.png',
              width: 30,
              height: 30,
            ),
          ),
        ),
        title: const Text(
          '会员权益',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        actions: [
          GestureDetector(
            child: const Padding(
              padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
              child: Text(
                '恢复内购',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.white,
                ),
              ),
            ),
            onTap: () {
              print('恢复内购');

              Common.loadingDialog(context);
              _type = 'repurchase';
              _loading = true;
              _buyEngin.resumePurchase();
            },
          )
        ],
      ),
      body: Container(
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: RadialGradient(
            center:
                Alignment.bottomLeft, // This approximates the '0% 55%' in CSS
            radius: 1.2, // This is the radius of the gradient
            colors: [
              Color(0xFF005820), // This is the '#145221' color
              Color(0xFF000000), // This is the '#060606' color
            ],
            stops: [0, 1], // Corresponds to '0%' and '100%' in CSS
          ),
        ),
        child: Scrollbar(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Stack(
                  children: [
                    Image.asset(
                      'assets/images/vip_bannar.png',
                      width: double.infinity,
                    ),
                    Positioned(
                      bottom: 15,
                      right: 0,
                      left: 0,
                      child: Column(
                        children: [
                          Image.asset(
                            'assets/images/vip_title_2.png',
                            width: 310,
                            height: 18,
                          ),
                          const SizedBox(
                            height: 11,
                          ),
                          Row(
                            children: [
                              const SizedBox(
                                width: 38,
                              ),
                              Image.asset(
                                'assets/images/avatars.png',
                                height: 23,
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                              const Text(
                                '10000+用户已开通  300000+音乐已创作',
                                style: TextStyle(
                                  fontSize: 11,
                                  color: Colors.white,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    // SizedBox(
                    //   height: 315,
                    // ),
                  ],
                ),

                const SizedBox(
                  height: 18,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ..._list.asMap().entries.map((entry) {
                      int index = entry.key; // 当前元素的索引
                      var info = entry.value; // 当前元素

                      return ItemWidget(
                        favorable: false,
                        activeIndex: _currentIndex,
                        index: index,
                        info: info,
                        artConsumeCoinNumber: _artConsumeCoinNumber,
                        onChanged: (i) {
                          setState(() {
                            _currentIndex = i;
                            _customId = _list[i].customId;
                            _id = _list[i].id;
                          });
                        },
                      );
                    }).toList(),
                  ],
                ),
                // Container(
                //   margin: const EdgeInsets.fromLTRB(23, 15, 23, 18),
                //   height: 31,
                //   padding: const EdgeInsets.only(left: 13),
                //   width: double.infinity,
                //   decoration: const BoxDecoration(
                //     image: DecorationImage(
                //       image: AssetImage('assets/images/vip_bg.png'),
                //     ),
                //   ),
                //   child: const Text(
                //     'AI音乐包 获得20首音乐创作机会',
                //     style: TextStyle(
                //       fontWeight: FontWeight.w500,
                //       fontSize: 11,
                //       color: Colors.white,
                //       height: 2.81,
                //     ),
                //   ),
                // ),
                const Padding(
                  padding: EdgeInsets.fromLTRB(35, 32, 35, 27),
                  child: Text(
                    '确认购买后，将向您的iTunes账户收款，如果选择自动续订，iTunes账户会在计费周期到期的前24小时扣费，在此之前，您可以在系统「设置」-「iTunesStore与App Store」-「App ID」里进行退订。更多条款请看： 《隐私政策》及《会员及续费协议》，开通即同意以上协议。',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Color(0xFFB6B6B6),
                      fontSize: 9,
                      height: 1.38,
                    ),
                  ),
                ),

                ButtonWidget(
                  onTap: () {
                    _buy(_customId);
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text(
                        '继续',
                        style: TextStyle(
                          fontSize: 15,
                          color: Color(0xFF000000),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Image.asset(
                        'assets/images/vip_bnt_right.png',
                        width: 29,
                        height: 10,
                      ),
                    ],
                  ),
                ),
                const SizedBox(
                  height: 50,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return PopupWidget(
            time: _time,
            goods: _year,
            buy: _buy,
          );
        });
  }
}
